<?php
		if ( $CFG->email_enable_ssl ) {
			$wwwroot = str_replace('http:','https:',$CFG->wwwroot);
	    } else {
	        $wwwroot = $CFG->wwwroot;
	    }
?>

<!--CSS file (default YUI Sam Skin) -->

<script type="text/javascript">
YUI().use('yui1-yahoo-dom-event', 'yui2-datasource', 'yui2-connection', 'yui2-json', 'yui2-autocomplete', function(Y) {
    var YAHOO = Y.YUI2;

    // An XHR DataSource
    var myServer = "<?php echo $wwwroot.'/blocks/email_list/email/participants/search_users.php';?>";
    var myDataSource = new YAHOO.util.XHRDataSource(myServer);
    myDataSource.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
    myDataSource.responseSchema = {
         resultsList : "ResultSet.Result",
         fields : ["Username", "Userid"]
    };

    // Define the dropdown lists and data sources
    var myAutoCompTo = new YAHOO.widget.AutoComplete("id_nameto","qResultsTo", myDataSource);
    var myAutoCompCC = new YAHOO.widget.AutoComplete("id_namecc","qResultsCC", myDataSource);
    var myAutoCompBCC = new YAHOO.widget.AutoComplete("id_namebcc","qResultsBCC", myDataSource);

    myAutoCompTo.generateRequest = function(sQuery) {
        return "?query=" + sQuery +"&course=<?php echo $course->id; ?>";
    }

    myAutoCompCC.generateRequest = function(sQuery) {
        return "?query=" + sQuery +"&course=<?php echo $course->id; ?>";
    }

    myAutoCompBCC.generateRequest = function(sQuery) {
        return "?query=" + sQuery +"&course=<?php echo $course->id; ?>";
    }

    //define your itemSelect handler function:
    var itemSelectHandler = function(sType, aArgs) {
        YAHOO.log(sType); //this is a string representing the event;
    				      //e.g., "itemSelectEvent"
    	var oMyAcInstance = aArgs[0]; // your AutoComplete instance

        var name = oMyAcInstance["_sName"];
        field = name.split(" ");

    	var elListItem = aArgs[1]; //the <li> element selected in the suggestion
            				       //container
    	var aData = aArgs[2]; //array of the data for the item as returned by the DataSource

        // To determine which of the three fields data is from
        var fieldid = field[1];
        var fieldtype = fieldid.substr(7,fieldid.length);

        // Checks if selected user was added already
        if (alreadySending("to", aData[1])) {
        	// Clear input value.
    		window.document.getElementById(fieldid).value = '';
            return false;
        }
        if (alreadySending("cc", aData[1])) {
        	// Clear input value.
    		window.document.getElementById(fieldid).value = '';
            return false;
        }
        if (alreadySending("bcc", aData[1])) {
    	    // Clear input value.
    		window.document.getElementById(fieldid).value = '';
            return false;
        }

        //for (myKey in elListItem){
        //	alert ("elListItem["+myKey +"] = "+elListItem[myKey]);
        //}

        var input = '<input type="hidden" value="'+aData[1]+'" name="'+fieldtype+'[]" />';

    	var rand = get_random();
        var fullname = window.document.createElement("span");
        fullname.setAttribute("id", fieldid+rand);
        fullname.setAttribute("class", "ajax_user_selected");

        window.document.getElementById(fieldid).parentNode.insertBefore(fullname,window.document.getElementById(fieldid));
        var htmlimg = '<img class="imgdropuser" src="<?php echo $wwwroot;?>/blocks/email_list/email/images/cross.png" height="11" width="11" alt="<?php echo get_string('remove','block_email_list');?>" />';
    	fullname.innerHTML = elListItem["textContent"]+'<a href="#" onclick="removeAJAXContact(\''+fieldid+rand+'\');">'+htmlimg+input+'</a>';

        // On selection of name, this fills out the hidden elements required to send
        // to selected user
        // I Very Hate IE...had to do this ugly hack to get this to work for IE 6+ :(
        var contacts = window.document.createElement("span");

    	window.document.getElementById(fieldid).parentNode.appendChild(contacts);
    	//contacts.innerHTML = '<input type="hidden" value="'+aData[1]+'" name="'+fieldtype+'[]" />';

    	// Clear input value.
    	window.document.getElementById(fieldid).value = '';
    };

    //subscribe your handler to the event for to field
    myAutoCompTo.itemSelectEvent.subscribe(itemSelectHandler);

    //subscribe your handler to the event for cc field
    myAutoCompCC.itemSelectEvent.subscribe(itemSelectHandler);

    //subscribe your handler to the event for bcc field
    myAutoCompBCC.itemSelectEvent.subscribe(itemSelectHandler);

    // Some settings (to field)
    myAutoCompTo.delimChar = ",";
    myAutoCompTo.maxResultsDisplayed = 5;
    myAutoCompTo.minQueryLength = 1;
    myAutoCompTo.queryDelay = 0;
    // Was causing problems with interaction between YUI autocomplete and contacts list popup, so its disabled
    myAutoCompTo.forceSelection = false;
    // Was causing some user interaction issues, so its disabled
    myAutoCompTo.typeAhead = false;
    myAutoCompTo.maxCacheEntries = 20;
    myAutoCompTo.queryMatchSubset = true;
    //Do not automatically highlight the first result item in the container
    myAutoCompTo.autoHighlight = true;


    // Some settings (cc field)
    myAutoCompCC.delimChar = ",";
    myAutoCompCC.maxResultsDisplayed = 5;
    myAutoCompCC.minQueryLength = 1;
    myAutoCompCC.queryDelay = 0;
    // Was causing problems with interaction between YUI autocomplete and contacts list popup, so its disabled
    myAutoCompCC.forceSelection = false;
    // Was causing some user interaction issues, so its disabled
    myAutoCompCC.typeAhead = false;
    myAutoCompCC.maxCacheEntries = 20;
    myAutoCompCC.queryMatchSubset = true;

    // Some settings (bcc field)
    myAutoCompBCC.delimChar = ",";
    myAutoCompBCC.maxResultsDisplayed = 5;
    myAutoCompBCC.minQueryLength = 1;
    myAutoCompBCC.queryDelay = 0;
    // Was causing problems with interaction between YUI autocomplete and contacts list popup, so its disabled
    myAutoCompBCC.forceSelection = false;
    // Was causing some user interaction issues, so its disabled
    myAutoCompBCC.typeAhead = false;
    myAutoCompBCC.maxCacheEntries = 20;
    myAutoCompBCC.queryMatchSubset = true;
});
/**
 * This function checks if user is added already
 *
 * @param string sentype 'to', 'cc', 'bcc'
 * @param string userid
 * @return boolean true if already sending, false if new participant
 */
function alreadySending(sendtype, userid) {
    var old = null;

    if (old = document.getElementsByName(sendtype+'[]')) {
        for (var i=0; i < old.length; i++) {
            if ( userid == old[i].value ) {
                return true;
            }
        }
    } else {
        return false;
    }
}

/**
 * This funcion remove a user selected by Ajax.
 *
 *
 */
function removeAJAXContact(fieldid) {
    var elm = document.getElementById(fieldid);
    elm.parentNode.removeChild(elm);
}

/**
 * Return random number.
 *
 */
function get_random() {
    var ranNum= Math.floor(Math.random()*7);
    return ranNum;
}
</script>